<?php

namespace app\api\controller\baiying;


use app\common\exception\UploadException;
use think\Config;
use think\Hook;
use baiying\lib\BYTokenClient;
use think\Db;

/**
 * 公共接口
 */
class Byaiphone extends Bybase {

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize() {
        parent::_initialize();
    }
    
    public function autoFenYeGetTaskPhone(){
        ignore_user_abort(true);    // 忽略客户端断开
        set_time_limit(0);        //设置执行不超时
        ini_set('memory_limit', '3096M');
        
        while (true){
            $callJoblist = db('ec_ai_task')->where('status','in',[0,1])->where('callJobId','3686152')->select();
            
            
            foreach ($callJoblist as $key => $value){
                
                db('ec_ai_task')->where('id',$value['id'])->setField('status',1);
                
                $currentPage = 1;
                $successCount = 0;
                $apiTotal = 0;
                $msg = '未知';
                
                $repeat_count = 0;
                $current_job_end = false; //当前任务是否结束
                $exist_info = db('ec_ai_task_phone_request')->where('callJobId',$value['callJobId'])->find();
                if(empty($exist_info)){
                    $uuid = md5(uniqid());
                    $id = db('ec_ai_task_phone_request')->insertGetId(['method'=>'ai_task_phone','callJobId'=>$value['callJobId'],'total'=>$value['totalCount'],
                        'uuid'=>$uuid,'createtime'=>time(),'status'=>1
                    ]);                    
                }else{
                    $repeat_count = $exist_info['repeat_count'];
                    $id = $exist_info['id'];
                    $currentPage = $exist_info['current_page'];
                }
                
                if($repeat_count > 3) continue;
                
                while(true){
                    $item_param = ['pageNum'=>$currentPage,'pageSize'=>100,'callJobId'=>$value['callJobId']];                  
                    $response = $this->getAiTaskPhoneList($item_param);


                    db('ec_ai_task_phone_request_page')->insert([
                        'ec_ai_task_phone_request_id'=>$id,
                        'request_param'=>json_encode($item_param,JSON_UNESCAPED_UNICODE),
                        'currentpage'=>$currentPage,
                        'config'=> json_encode($response,JSON_UNESCAPED_UNICODE),
                        'createtime'=>time()
                    ]);


                    if($response['code'] == 200){                        
                        $this->taskPhoneInsert($response['data']['list']);
                        $successCount = $successCount + count($response['data']['list']);
                        $apiTotal = $response['data']['total'];
                        $currentPage = $response['data']['pageNum'] + 1;
                        if($currentPage > $response['data']['pages']){
                            $msg = '成功';
                            $current_job_end = true;
                        }                                
                    }else{
                        $msg = '失败';
                        $current_job_end = true;
                    }    
               
                    
                    if($current_job_end)  break;
                }
                $status = $successCount >= $value['totalCount'] ? 2 : 1;
                db('ec_ai_task_phone_request')->where('id',$id)->update([
                    'current_page' =>$currentPage,
                    'api_total'=>$apiTotal,
                    'success_total'=>$successCount,
                    'repeat_count'=>$repeat_count + 1,
                    'status'=>$status,
                    'msg'=>$msg,
                    'endtime'=>time()
                ]);
                if($status == 2){
                    db('ec_ai_task')->where('id',$value['id'])->setField('status',2);
                }
                
                
                
                
            }
            
            
            break;
            
            
              
        }
        
        exit('aaa');
        
        
        
    }

    
    public function getAiTaskPhoneList($request_data) {
        
        $client = new BYTokenClient($this->access_token);

        $method = 'byai.openapi.calljob.calldone.list'; //要调用的api名称
        $api_version = '1.0.0'; //要调用的api版本号
        

        $my_params = ['companyId' => $this->companyId,'callJobId'=>$request_data['callJobId'],'pageNum'=>$request_data['pageNum'],'pageSize'=>$request_data['pageSize']];
        $my_files = [];

        $result = $client->post($method, $api_version, $my_params, $my_files);
        
        return $result;
        
    }
    
    
    public function taskPhoneInsert($data){
        if(empty($data)) return false;
        
        $fields_list = Db::getFields('fa_ec_ai_task_phone');
        $fields = array_keys($fields_list);
        $paichu_fields = ['id','createtime','config','status'];
        $end_fields = array_diff($fields,$paichu_fields);
        
        $end_data = [];
        foreach ($data as $value){
            
            $is_exist = db('ec_ai_task_phone')->where('callInstanceId',$value['callInstanceId'])->count();
            if(!empty($is_exist)) continue;
            
            
            
            
            $resultList = $value['resultList'];
            if(!empty($resultList[0]['name']) && $resultList[0]['name'] == '客户意向等级'){
                preg_match('/[a-zA-Z]/', $resultList[0]['value'], $matches);
                $value['is_yixiang'] = 1;
                $value['yixiang_txt'] = $resultList[0]['value'];
                $value['yixiang_value'] = !empty($matches[0])?$matches[0]:'';                
            }else{
                $value['is_yixiang'] = 0;
            }
            $value['origin'] = 1;
            if(empty($value['yixiang_value']))                continue;
            if(!empty($value['yixiang_value'])){
                if(!in_array($value['yixiang_value'], ['A','B','C','D'])){
                    continue;
                }
            }
            
            foreach ($end_fields as $v){
                $middle_data[$v] = empty($value[$v]) ? '' : $value[$v];
            }
            
            $middle_data['createtime'] = time();
            $middle_data['config'] = json_encode($value,JSON_UNESCAPED_UNICODE);
            
            
            $end_data[] = $middle_data;
            
        }
        
        if(empty($end_data)) return false;
        db('ec_ai_task_phone')->insertAll($end_data);
    }
    

}
